@echo off

:init
set SRV_NAME=ikanda
set SRV_TITLE=Ikanda Web Pages And Service
set SRV_DESCRIPTION=An easy-to-use tool to deploy package to multiple nodes.

:check
rem check python
echo Checking requirements ...
if "%PYTHON_HOME%"=="" goto err_no_python_env
if not exist "%PYTHON_HOME%\python.exe" goto err_no_python
echo All requirements satisfied 

rem check nssm
if not exist "nssm.exe" goto err_no_nssm

:create
rem create service
echo Creating service %SRV_NAME% ...
nssm install ikanda "%PYTHON_HOME%\python"
if not %ERRORLEVEl% == 0 goto err_create_service
echo Service %SRV_NAME% created

rem set service parameters
echo Set parameters...
nssm set ikanda AppParameters -m gevent.pywsgi -b 0.0.0.0:5000 wsgi:app
nssm set ikanda AppDirectory %~dp0
nssm set ikanda DisplayName %SRV_TITLE%
nssm set ikanda Description %SRV_DESCRIPTION%
nssm set ikanda Start SERVICE_AUTO_START
nssm set ikanda ObjectName LocalSystem
nssm set ikanda Type SERVICE_WIN32_OWN_PROCESS
nssm set ikanda AppStdout %~dp0service-stdout.log
nssm set ikanda AppStderr %~dp0service-stderr.log
nssm set ikanda AppRotateFiles 1
nssm set ikanda AppRotateOnline 0
nssm set ikanda AppRotateSeconds 86400
nssm set ikanda AppRotateBytes 1048576
nssm set ikanda AppStopMethodSkip 6
nssm set ikanda AppStopMethodConsole 6000
nssm set ikanda AppThrottle 10000
nssm set ikanda AppExit Default Restart
nssm set ikanda AppRestartDelay 5000
echo All parameters set

:start
rem start service
echo Starting service %SRV_NAME%
if not exist "logs" md logs
net start %SRV_NAME%
if not %ERRORLEVEl% == 0 goto err_start_service
echo Service %SRV_NAME% started
goto end

:err_no_python_env
echo Env "PYTHON_HOME" not found
goto end

:err_no_python
echo %PYTHON_HOME%\python.exe not found
goto end

:err_no_nssm
echo NSSM.exe not found
goto end

:err_create_service
echo Cannot create service %SRV_NAME%
goto end

:err_start_service
echo Cannot start service %SRV_NAME%
goto end

:end
rem reset all variables and colors
set SRV_NAME=
color
echo on